package com.alibaba.fastjson;

import java.util.HashMap;
import java.util.Map;

public class JSONClassReferencer implements ClassReferencer {

	Map<String, Integer> class2indexes;
	int currentIndex = 0;

	public int getClassIndex(String className) {
		if (class2indexes != null) {
			if (class2indexes.containsKey(className)) {
				return class2indexes.get(className).intValue();
			}
		}
		return -1;
	}

	public int addClassIndex(String className) {
		if (class2indexes == null) {
			class2indexes = new HashMap<String, Integer>();
		}
		if (class2indexes.containsKey(className)) {
			return class2indexes.get(className).intValue();
		}
		int index = currentIndex;
		currentIndex++;
		class2indexes.put(className, index);
		return index;
	}

	Map<Integer, String> index2classes;

	public String getClassName(int index) {
		if (index2classes == null)
			return null;
		Integer key = Integer.valueOf(index);
		if (index2classes.containsKey(key)) {
			return index2classes.get(key);
		}
		return null;
	}

	public void addIndexClass(int index, String className) {
		if (index2classes == null) {
			index2classes = new HashMap<Integer, String>();
		}
		Integer key = Integer.valueOf(index);
		if (index2classes.containsKey(key)) {
			throw new java.lang.IllegalStateException("index exists:" + index
					+ "->" + index2classes.get(key));
		}
		index2classes.put(key, className);
	}

	public void reset() {
		if (index2classes != null)
			index2classes.clear();
		if (class2indexes != null)
			class2indexes.clear();
		currentIndex = 0;
	}
	
	public String handleTypeName(String typeName) {
		if (typeName.startsWith(JSON.DEFAULT_TYPE_REF_PREFIX)) {
			int index = Integer.parseInt(
					typeName.substring(JSON.DEFAULT_TYPE_REF_PREFIX.length()),
					10);
			typeName = this.getClassName(index);
		} else {
			int pos = typeName.lastIndexOf(JSON.DEFAULT_TYPE_REF_PREFIX);
			if (pos > 0) {
				int index = Integer.parseInt(
						typeName.substring(pos
								+ JSON.DEFAULT_TYPE_REF_PREFIX.length()), 10);
				typeName = typeName.substring(0, pos);
				this.addIndexClass(index, typeName);
			} else {
				//
			}
		}
		return typeName;
	}
}
